const express = require('express');
const path = require('path');
const app = express();

// 使用静态资源
app.use(express.static("public"))
app.binaryTypes = ['*/*'];

// 设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Routes
app.get(`/`, (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/test', (req, res) => {
  res.render('index', {title: '我是标题'});
})

app.get('/user', (req, res) => {
  res.json({
    user: {
      name: '侯恭超',
      age: 72,
      gender: 'male',
      hobby: ['sleep', 'eat']
    },
    code: 200,
    success: true,
    message: '成功'
  })
});

app.get('/user/:id', (req, res) => {

  res.json({
    user: {
      name: '孟雅娇',
      age: 88,
      gender: 'male',
      hobby: ['sleep', 'eat']
    },
    code: 200,
    success: true,
    message: '成功'
  })
});

app.get('/404', (req, res) => {
  res.status(404).send('Not found');
});

app.get('/500', (req, res) => {
  res.status(500).send('Server Error');
});

// Error handler
app.use(function (err, req, res, next) {
  console.error(err);
  res.status(500).send('Internal Serverless Error');
});

module.exports = app;
